<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <link rel="icon" href="/favicon.ico" />
    <link rel="stylesheet" href="/assets/vendor/bootstrap/dist/css/bootstrap.min.css" />
    <title>上传</title>
  </head>
  <body>
    <div id="app" style="padding-top: 48px;">
      <div class="container">
        <form>
          <div class="form-group">
            <label for="exampleInputFile">文件:</label>
            <input id="file" class="form-control-file" type="file">
          </div>
          <div class="form-group">
            <label for="exampleInputFile">进度:</label>
            <div class="progress">
              <div id="progress" class="progress-bar" role="progressbar" style="width: 0%"></div>
            </div>
          </div>
          <button id="submit" type="button" class="btn btn-primary">上传</button>
        </form>
      </div>
    </div>
    <script>
      let formData
      // 获取 input file 的 dom 对象
      const inputFile = document.querySelector('#file');
        // 监听 change 事件
        inputFile.addEventListener('change', function() {
        // 使用 formData 装载 file
        formData = new FormData();
        formData.append('file', this.files[0]);
      })

      // 上传文件
      document.querySelector('#submit').addEventListener('click', function () {
        if (!formData) {
          alert('请选择文件')
          return false
        }
        upload(formData)
      }, false)

      // 上传
      const upload = ( formData ) => {
        const xhr = new XMLHttpRequest();
          // 监听文件上传进度
          xhr.upload.addEventListener('progress', function(e) {
          if (e.lengthComputable) {
            // 获取进度
            const progress = Math.round((e.loaded * 100) / e.total);
            document.querySelector('#progress').style.width = progress + '%';
          }
        },false);
        // 监听上传完成事件
        xhr.addEventListener('load', ()=>{
          console.log(':smile:上传完成')
        }, false);
        xhr.open('post', '/upload');
        xhr.send(formData);
      }
    </script>
  </body>
</html>